package com.thinkgem.jeesite.modules.quartz;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.guest.entity.UsAttendanceGuest;
import com.thinkgem.jeesite.modules.guest.service.UsAttendanceGuestService;

@Service("fileProcessGuestJob")
public class FileProcessGuestJob {

    // 原始目录
    public final String              guestSrcDirName       = Global.getUserfilesBaseDir()
                                                             + Global.getConfig("guestSrcDirName");
    // 中转目录
    public final String              guestTransferDirName  = Global.getUserfilesBaseDir()
                                                             + Global.getConfig("guestTransferDirName");
    // 中转目录,真是存放文件地址
    public final String              guestTransferDirName2 = Global.getUserfilesBaseDir()
                                                             + Global.getConfig("guestTransferDirName2");
    // 备份目录
    public final String              guestBackupsDirName   = Global.getUserfilesBaseDir()
                                                             + Global.getConfig("guestBackupsDirName");
    /**
     * 日志
     */
    private static final Log         log                   = LogFactory.getLog(FileProcessGuestJob.class);

    @Autowired
    private UsAttendanceGuestService usAttendanceGuestService;

    /**
     * 定时任务拷贝及处理文件.
     */
    public void doSomeThing() {
        try {
            // copy文件到指定中专目录
            boolean result = FileUtils.copyDirectoryCover(guestSrcDirName, guestTransferDirName, true);
            if (result) {
                // 删除上传过的原文件
                FileUtils.deleteDirectory2(guestSrcDirName);
            } else {
                return;
            }

            // 解析文件，把数据放到数据库
            // 列出源目录下的所有文件名和子目录名
            File srcDir = new File(guestTransferDirName2);
            File[] files = srcDir.listFiles();
            if (files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].isFile()) {
                        String fileName = files[i].getAbsolutePath();
                        // 如果是一个单个文件，则直接复制
                        importFile(fileName);
                        String newFileName = guestBackupsDirName + files[i].getName();
                        // 拷贝文件
                        boolean flag = FileUtils.copyFileCover(fileName, newFileName, true);
                        if (flag) {
                            // 删除原始文件
                            FileUtils.deleteFile(fileName);
                        }
                    }
                }
            }
            log.info("测试定时任务2222..............................");
            System.out.println("测试定时任务22222..............................");
        } catch (Exception e) {
            log.error("美国外包定时任务拷贝及处理文件错误" + e.getMessage(), e);
            e.printStackTrace();
        }

    }

    /**
     * 导入用户数据
     * 
     * @param file
     * @param redirectAttributes
     * @return
     */
    public void importFile(String fileName) {

        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(fileName, 1, 0);
            UsAttendanceGuest guest = null;
            // 获取周一日期
            String strDate = null;

            for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {
                try {
                    Row row = ei.getRow(i);

                    String employeeId = null;
                    String lastName = null;
                    String firstName = null;
                    if (0 == i || 1 == i || 2 == i) {
                        continue;
                    }
                    if (3 == i) {
                        for (int n = 0; n < ei.getLastCellNum(); n++) {
                            Object val = ei.getCellValue(row, n);
                            if (3 == n) {
                                String str = String.valueOf(val);
                                strDate = str.substring(12, 22);
                                break;
                            }
                        }
                        continue;
                    }// end if

                    for (int j = 0; j < ei.getLastCellNum(); j++) {

                        Object val = ei.getCellValue(row, j);
                        if (0 == j) {
                            if (null == val || String.valueOf(val).length() <= 0) {
                                break;
                            }
                        }

                        switch (j) {
                            case 0:
                                employeeId = substr(String.valueOf(val));
                                break;
                            case 1:
                                lastName = String.valueOf(val);
                                break;
                            case 2:
                                firstName = String.valueOf(val);
                                break;
                            case 3:
                                guest = new UsAttendanceGuest();
                                guest.setEmployeeId(employeeId);
                                guest.setLastName(lastName);
                                guest.setFirstName(firstName);
                                SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy");
                            	Date date = sdf.parse(String.valueOf(strDate));
                                guest.setDate(date);
                                guest.setDatevalue(String.valueOf(val));
                                usAttendanceGuestService.save(guest);
                                break;
                            case 4:
                                guest = new UsAttendanceGuest();
                                guest.setEmployeeId(employeeId);
                                guest.setLastName(lastName);
                                guest.setFirstName(firstName);
                                guest.setDate(getDate(strDate, 1));
                                guest.setDatevalue(String.valueOf(val));
                                usAttendanceGuestService.save(guest);
                                break;
                            case 5:
                                guest = new UsAttendanceGuest();
                                guest.setEmployeeId(employeeId);
                                guest.setLastName(lastName);
                                guest.setFirstName(firstName);
                                guest.setDate(getDate(strDate, 2));
                                guest.setDatevalue(String.valueOf(val));
                                usAttendanceGuestService.save(guest);
                                break;
                            case 6:
                                guest = new UsAttendanceGuest();
                                guest.setEmployeeId(employeeId);
                                guest.setLastName(lastName);
                                guest.setFirstName(firstName);
                                guest.setDate(getDate(strDate, 3));
                                guest.setDatevalue(String.valueOf(val));
                                usAttendanceGuestService.save(guest);
                                break;
                            case 7:
                                guest = new UsAttendanceGuest();
                                guest.setEmployeeId(employeeId);
                                guest.setLastName(lastName);
                                guest.setFirstName(firstName);
                                guest.setDate(getDate(strDate, 4));
                                guest.setDatevalue(String.valueOf(val));
                                usAttendanceGuestService.save(guest);
                                break;
                            case 8:
                                guest = new UsAttendanceGuest();
                                guest.setEmployeeId(employeeId);
                                guest.setLastName(lastName);
                                guest.setFirstName(firstName);
                                guest.setDate(getDate(strDate, 5));
                                guest.setDatevalue(String.valueOf(val));
                                usAttendanceGuestService.save(guest);
                                break;
                            case 9:
                                guest = new UsAttendanceGuest();
                                guest.setEmployeeId(employeeId);
                                guest.setLastName(lastName);
                                guest.setFirstName(firstName);
                                guest.setDate(getDate(strDate, 6));
                                guest.setDatevalue(String.valueOf(val));
                                usAttendanceGuestService.save(guest);
                                break;
                            default:

                                break;
                        }// end switch
                    }// end for

                    successNum++;
                    System.out.print("\n");
                } catch (Exception e) {
                    // TODO: handle exception
                    failureNum++;
                }
            }// end for
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
            }
            // addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户" +
            // failureMsg);
        } catch (Exception e) {
            log.error("美国外包定时解析文件错误" + e.getMessage(), e);
            e.printStackTrace();
        }

    }

    /**
     * 根据指定时间增长.
     * 
     * @param para
     * @param next
     * @return
     */
    public Date getDate(String para, int next) {
        String strDate = null;
        Date date;
        Date returnDate=null;
        try {
            date = (new SimpleDateFormat("mm/dd/yyyy")).parse(para);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DATE, next);
            strDate = (new SimpleDateFormat("mm/dd/yyyy")).format(cal.getTime());
            
            SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy");
            returnDate = sdf.parse(String.valueOf(strDate));
        	
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("美国外包定时解析文件中的日期错误" + e.getMessage(), e);
        }
        
        return returnDate;
    }
   /**
    * 
    * 根据特殊字符截取数据.
    * @param para
    * @return
    */
    public String substr(String para) {
        int index = para.indexOf(".");
        if (index > 0) {
            return para.substring(0, index);
        } else {
            return para;
        }

    }

}
